package cn.lil.servlet;

import cn.lil.dao.OrderItemDao;
import cn.lil.model.Order;
import cn.lil.model.OrderItem;
import cn.lil.model.User;
import cn.lil.service.OrderItemService;
import cn.lil.service.OrderService;
import com.oracle.wls.shaded.org.apache.xpath.operations.Or;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.*;

import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@WebServlet(name = "OrderItemDeleteServlet", value = "/OrderItemDeleteServlet")
public class OrderItemDeleteServlet extends HttpServlet {
    OrderService orderService = new OrderService();
    OrderItemService orderItemService = new OrderItemService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int orderItemId = Integer.parseInt(request.getParameter("itemId"));
        User u = (User) request.getSession().getAttribute("user");
//        OrderItem orderItemOne = null;
        try {
            orderService.deleteOrderItem(orderItemId);
//            orderItemOne = orderItemService.getItemById(orderItemId).get(0);
        } catch (SQLException e) {
            e.printStackTrace();
        }
//        删除操作完成之后重新在数据库中获取当前用户的order下的item
        Order o = (Order) request.getSession().getAttribute("order");
        List<OrderItem> orderItemList;
        try {
            //            重新在数据库中获取当前用户的order的新的item列表数据
            orderItemList = orderService.selectAllitem(o.getId());
            int a = 0;
            float tf = 0f;
            for (OrderItem oi : orderItemList) {
                a += oi.getAmount();
                tf += oi.getPrice();
            }
            orderService.updateOrderAmountAndtotal(o.getId(), u.getId(), a, tf);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        o.setItemList(orderItemList);
//        刷新会话中的order对象
        request.getSession().setAttribute("order", o);
        response.getWriter().write("ok");
        request.getRequestDispatcher("/OrderListServlet").forward(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int orderItemId = Integer.parseInt(request.getParameter("itemId"));
        try {
            orderService.deleteOrderItem(orderItemId);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        response.getWriter().write("ok");
        request.getRequestDispatcher("/OrderItemListServlet").forward(request, response);
    }
}
